package com.simon.app.october.modules.sys.oauth2;

import com.simon.app.october.modules.sys.entity.SysUserEntity;
import com.simon.app.october.modules.sys.entity.SysUserTokenEntity;
import com.simon.app.october.modules.sys.service.ShiroService;
import com.simon.app.october.modules.sys.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class Oauth2Realm extends AuthorizingRealm {

    @Autowired
    private SysUserService  userService;

    @Autowired
    private ShiroService    shiroService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Oauth2Token;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        // 获取用户实体
        SysUserEntity user = (SysUserEntity) principal.getPrimaryPrincipal();
        long userId = user.getUserId();
        // 获取权限列表
        Set<String> list = shiroService.getUserPermissions(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(list);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        /**
         * 根据token来查找用户
         * */
        String accessToken = (String) token.getPrincipal();

        SysUserTokenEntity tokenEntity = shiroService.findByToken(accessToken);

        // token失效判断
        if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }

        // 查询用户信息
        SysUserEntity userEntity = userService.findById(tokenEntity.getUserId());


        if (null == userEntity) {
            throw new AuthenticationException("用户不存在");
        }

        return new SimpleAuthenticationInfo(
                userEntity,
                accessToken,
                getName()
        );
    }
}
